package servlet;

import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String account = request.getParameter("account");
		String pwd = request.getParameter("pwd");
		String surePwd = request.getParameter("sure_pwd");
		String userName = request.getParameter("userName");

		UserDao dao = new UserDao();
		int retSureAccount = dao.sure_user(account);
		if(retSureAccount >= 1){
			//用户名已存在
			request.getSession().setAttribute("errorMsg", "用户名已存在");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}
		if(!pwd.equals(surePwd)){
			//两次密码输入不一致
			request.getSession().setAttribute("errorMsg", "两次密码输入不一致");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}else{
			int retInsertUser = dao.regist(account,userName,pwd);
			if(retInsertUser >= 1){
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}
	}
}
